/**
 * Copyright (c) 2020-2021 浦东大爷 All rights reserved.
 * 机会永远都是留给有准备的人
 */
package com.lagou.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageInfo;
import com.lagou.common.Const;
import com.lagou.common.ResponseCode;
import com.lagou.common.ServerResponse;
import com.lagou.model.User;
import com.lagou.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author: gitwo
 * @date: 2021-03-08
 * @description:
 */
@Controller
@RequestMapping("/user")
public class Usercontroller {

    @Autowired
    private IUserService iUserService;

    /**
     * 1. 用户登录
     */
    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session){
        // 1. 调用service的登录方法，会返回一个serverResponse<User>
        ServerResponse<User> response = iUserService.login(username, password);
        // 2. 判断是否登录成功，登录成功把当前用户放到session中
        if(response.getStatus() == ResponseCode.SUCCESS.getCode()){
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }
        // 3. 返回serverResponse
        return response;
    }

    /**
     * 分页查找
     */
    @RequestMapping(value = "list.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<PageInfo> list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){
        ServerResponse<PageInfo> users = iUserService.getUser(pageNum, pageSize);
        return users;
    }

    /**
     *添加用户
     */
    @RequestMapping(value = "add.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> add(User user){
        return iUserService.add(user);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping(value = "del.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> delete(Integer id){
        return iUserService.delete(id);
    }

    /**
     * 更新修改用户
     * @param user
     * @return
     */
    @RequestMapping(value = "update.do", method = RequestMethod.POST)
    @ResponseBody
    public  ServerResponse<String> update(User user){
        return iUserService.update(user);
    }

    /**
     * getUserById 根据用户id获取用户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getUserById.do", method = RequestMethod.POST)
    @ResponseBody
    public  ServerResponse<Object> getUserById(Integer id){
        return iUserService.findById(id);
    }
}
